// pages/shoppingMall/detail.js
const app = getApp()
var topOpacity = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 组件参数设置，传递到组件
    defaultData: {
      title: "商品详情", // 导航栏标题
      showHome: false, //是否显示回到首页按钮
      showBack: true, //是否显示返回按钮
      showLogo: false, //是否显示logo
      bgColor: 'transparent',
      isShare: 0,
    },
    requestUrl: app.baseUrl,
    baseUrl: app.baseUrl,
    version: app.globalData.version,
    navBarHeight: app.globalData.navBarHeight,
    bannerArr: [],
    indicatorDots: true,
    autoplay: true,
    interval: 2000,
    duration: 500,
    btnText: "加入购物车",
    showChildGoods: false,
    showShoppingCart: false,
    specificationsArr: [],
    curSpecifications: 0,
    specsImg: '',
    inventory: 0,
    childGoodsPrice: 0,
    childOriginalPrice: 0,
    childGoodsNum: 1,
    totalAmount: 0,
    totalNum: 0,
    shoppingCart: [],

    shareTitle: '',
    shareImg: '',
    openid: '',
    id: 0,
    minSellingPrice: 0,
    maxOriginalPrize: 0,
    yxTotal: 0,
    commentTotal: 0,
    goodsInfo: [],
    noRegisterContent: '',
    is_login: 0,
    mySf: '',
    flag: 0
  },
  onPageScroll(t) {
    if (t.scrollTop < 40) {
      topOpacity = 0
      if (this.data.topOpacity != 0) {
        this.setData({
          topOpacity: 0
        })
      }
    } else if (t.scrollTop >= 40) {
      if (topOpacity <= 1) {
        topOpacity = t.scrollTop / 100 - .4
      } else {
        topOpacity = 1
      }
      if (topOpacity <= 1) {
        this.setData({
          topOpacity: topOpacity
        })
      }
    }
  },
  preventTouchMove() {
    return false;
  },
  /**
   * 选择子商品
   * 此方法用于处理选择子商品的操作。
   * 它会设置相关的数据，包括显示子商品的状态、子商品数量、当前规格 ID、库存、子商品价格、子商品原价以及总金额。
   * 数据均基于规格数组中的第一个元素进行初始化。
   */
  chooseChildGoods() {
    let that = this;
    that.setData({
      showChildGoods: true,
      childGoodsNum: 1,
      curSpecifications: that.data.specificationsArr[0].id,
      inventory: that.data.specificationsArr[0].inventory,
      childGoodsPrice: that.data.specificationsArr[0].price,
      childOriginalPrice: that.data.specificationsArr[0].originalPrice,
      btnText: "加入购物车"
    })
  },
  //打开购物车
  openShoppingCart() {
    let that = this;
    that.setData({
      showShoppingCart: true,
      showChildGoods: false,
      btnText: "结算购物车"
    });
    console.log('shoppingCart', that.data.shoppingCart);
  },
  closeShoppingCart() {
    let that = this;
    that.setData({
      showShoppingCart: false,
      btnText: '加入购物车'
    })
  },
  closeChildGoods() {
    this.setData({
      showChildGoods: false,
    })
  },

  /**
   * 处理选择商品规格的事件
   * @param {Event} e - 触发事件的对象，包含当前选中规格的 id 数据
   * 此函数用于更新当前选中的商品规格及相关信息，包括库存、价格等
   */
  chooseSpecifications(e) {
    let that = this;
    let id = e.currentTarget.dataset.id;
    let specificationsArr = that.data.specificationsArr;
    let index = specificationsArr.findIndex(item => item.id === id);
    that.setData({
      curSpecifications: id,
      childGoodsNum: 1,
      inventory: that.data.specificationsArr[index].inventory,
      childGoodsPrice: that.data.specificationsArr[index].price,
      childOriginalPrice: that.data.specificationsArr[index].originalPrice,
      specsImg: that.data.specificationsArr[index].imgPath
    })
  },
  goodsNumBlur(e) {
    let that = this;
    console.log(e)
    let goodsNum = e.detail.value;
    if (goodsNum > that.data.inventory) {
      that.setData({
        childGoodsNum: that.data.inventory
      })
    }
  },
  /**
   * 增加商品数量的函数。
   * 检查当前选择的商品数量是否小于库存，如果是，则增加商品数量并更新库存和总金额。
   * @function add
   * @memberof pages/shoppingMall/detail
   * @instance
   */
  add() {
    let that = this;
    let childGoodsNum = that.data.childGoodsNum;
    if (childGoodsNum >= that.data.inventory) {
      return;
    }
    childGoodsNum++;
    that.setData({
      childGoodsNum
    })
  },
  /**
   * 减少子商品数量的方法。
   * 当子商品数量大于1时，此方法会减少子商品数量，并相应地更新库存和总金额。
   * 它会减少子商品数量，重新计算库存（减去新的子商品数量），并更新总金额（新的子商品数量乘以单价）。
   * 最后，它使用 setData 方法来更新页面数据。
   */
  reduce() {
    let that = this;
    let childGoodsNum = that.data.childGoodsNum;
    if (childGoodsNum > 1) {
      childGoodsNum--;
      that.setData({
        childGoodsNum,
      })
    }

  },

    //处理价格是整型还是浮点型数字
    gshNum(num) {
      if (!isNaN(num) && parseInt(num, 10) === parseFloat(num)) {
        //为整型
        return parseInt(num);
      } else {
        //为浮点型 保留两位小数
        return parseFloat(parseFloat(num).toFixed(2));
      }
    },

  /**
   * 处理加入购物车的逻辑
   * @function pay
   * @description 当按钮文本为“加入购物车”时，执行以下操作：
   * 1. 根据商品ID查找商品规格数组中的对应商品。
   * 2. 检查购物车中是否已有该商品：
   *    - 若有，更新商品数量和总价。
   *    - 若无，添加新商品到购物车并计算数量和总价。
   * 3. 更新库存数量。
   * 4. 同步购物车数据和库存到本地存储。
   * 5. 显示成功提示并打印购物车数据。
   * @param {Object} that - 当前页面的上下文对象，包含数据和状态信息。
   */
  pay() {
    let that = this;
    //检查是否登录
    if (!this.checkLogin()) {
      return;
    }

    let btnText = that.data.btnText;
    if (btnText == "加入购物车") {
      //判断是否是业主专项
      if (that.data.goodsInfo.is_yz_share == 1 && that.data.mySf != '业主') {
        app.showTip('此商品仅限业主专项哦');
        return;
      }
      if (!that.data.showChildGoods) {
        that.setData({
          showChildGoods: true
        });
        return;
      }
      let id = that.data.curSpecifications;
      let specificationsArr = that.data.specificationsArr;
      let index = specificationsArr.findIndex(item => item.id === id);
      let shoppingCart = that.data.shoppingCart;
      let goodsName = that.data.goodsInfo.img_path;
      let addSjc = that.getThisSjc();
      let shop_id = that.data.shop_id;
      if (shoppingCart.length > 0) {
        let shoppingCartIndex = shoppingCart.findIndex(item => item.id === id);
        if (shoppingCartIndex != -1) {
          shoppingCart[shoppingCartIndex].num += that.data.childGoodsNum;
          shoppingCart[shoppingCartIndex].totalAmount = that.gshNum(that.gshNum(shoppingCart[shoppingCartIndex].num) * that.gshNum(shoppingCart[shoppingCartIndex].price));
          shoppingCart[shoppingCartIndex].goodsName = that.data.goodsInfo.goods_name;
          shoppingCart[shoppingCartIndex].imgPath = goodsName;
          shoppingCart[shoppingCartIndex].addSjc = addSjc;
          shoppingCart[shoppingCartIndex].unit = that.data.goodsInfo.unit;
          shoppingCart[shoppingCartIndex].shop_id = shop_id;
        } else {
          shoppingCart.push(specificationsArr[index]);
          shoppingCartIndex = shoppingCart.findIndex(item => item.id === id);
          shoppingCart[shoppingCartIndex].num = that.data.childGoodsNum;
          shoppingCart[shoppingCartIndex].totalAmount = that.gshNum(that.gshNum(that.data.childGoodsNum) * that.gshNum(shoppingCart[shoppingCartIndex].price));
          shoppingCart[shoppingCartIndex].goodsName = that.data.goodsInfo.goods_name;
          shoppingCart[shoppingCartIndex].imgPath = that.data.goodsInfo.img_path;
          shoppingCart[shoppingCartIndex].addSjc = addSjc;
          shoppingCart[shoppingCartIndex].unit = that.data.goodsInfo.unit;
          shoppingCart[shoppingCartIndex].shop_id = shop_id;
        }
      } else {
        shoppingCart.push(specificationsArr[index]);
        let shoppingCartIndex = shoppingCart.findIndex(item => item.id === id);
        shoppingCart[shoppingCartIndex].num = that.data.childGoodsNum;
        shoppingCart[shoppingCartIndex].totalAmount = that.gshNum(that.gshNum(that.data.childGoodsNum) * that.gshNum(shoppingCart[shoppingCartIndex].price));
        shoppingCart[shoppingCartIndex].goodsName = that.data.goodsInfo.goods_name;
        shoppingCart[shoppingCartIndex].imgPath = that.data.goodsInfo.img_path;
        shoppingCart[shoppingCartIndex].addSjc = addSjc;
        shoppingCart[shoppingCartIndex].unit = that.data.goodsInfo.unit;
        shoppingCart[shoppingCartIndex].shop_id = shop_id;
      }

      let totalAmount = shoppingCart.reduce((total, item) => that.gshNum(that.gshNum(total) + that.gshNum(item.totalAmount)), 0);
      let totalNum = shoppingCart.reduce((total, item) => total + item.num, 0);
      that.setData({
        shoppingCart,
        totalAmount,
        totalNum
      });
      wx.setStorageSync('shoppingCart' + that.data.shop_id, shoppingCart);

      app.showTip("成功加入购物车");
      console.log("购物车数据： ", shoppingCart)
    } else {
      //计算购物车
      //判断购物车是否为空
      if (that.data.shoppingCart.length <= 0) {
        app.showTip('您购物车暂无商品哦');
        return;
      } else {
        for (let i = 0; i < that.data.shoppingCart.length; i++) {
          if (that.data.shoppingCart[i].inventory < that.data.shoppingCart[i].num) {
            app.showTip('您购物车中第' + [i + 1] + '件商品所选数量超过了库存数量');
            return;
          }
        }
      }
      //提交数据至订单
      if (that.data.flag == 0) {
        that.setData({
          flag: 1
        });
        wx.showLoading({
          title: '订单创建...',
          mask: true
        });

        //发起网络请求
        wx.request({
          url: that.data.baseUrl + 'addShopOrderInfo.php',
          method: 'POST',
          data: {
            'openid': that.data.openid,
            'shoppingCar': JSON.stringify(that.data.shoppingCart),
            'shop_id': that.data.shop_id,
            'totalAmount': that.data.totalAmount
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: function (res) {
            wx.hideLoading();
            app.showTip(res.data.msg);
            if (res.data.status == 1) {
              //清空购物车
              wx.setStorageSync('shoppingCart' + that.data.shop_id, []);
              that.setData({
                shoppingCart: [],
                totalAmount: 0,
                totalNum: 0
              });
              setTimeout(function () {
                wx.navigateTo({
                  url: '/pages/shoppingMall/order?orderId=' + res.data.orderId + "&shop_id=" + that.data.shop_id
                });
              }, 1500);
            } else {
              if (res.data.is_show_del_tips == 1) {
                //删除购物车中特定id的商品
                var delCarList = res.data.delCarList;
                var shoppingCar = that.data.shoppingCart;
                var newShoppingCar = [];
                for (var i = 0; i < delCarList.length; i++) {
                  for (var j = 0; j < shoppingCar.length; j++) {
                    if (parseInt(delCarList[i]) != parseInt(shoppingCar[j].id)) {
                      newShoppingCar.push(shoppingCar[j]);
                    }
                  }
                }
                console.log(newShoppingCar, 'newShoppingCar')
                var totalAmount = newShoppingCar.reduce((total, item) => that.gshNum(that.gshNum(total )+ that.gshNum(item.totalAmount)), 0);
                var totalNum = newShoppingCar.reduce((total, item) => total + item.num, 0);
                that.setData({
                  shoppingCart: newShoppingCar,
                  totalAmount: totalAmount,
                  totalNum: totalNum
                });
                //更新缓存
                wx.setStorageSync('shoppingCart' + that.data.shop_id, newShoppingCar);
              }
            }
            that.setData({
              flag: 0
            });
            return;
          },
          fail: function () {
            that.setData({
              flag: 0
            });
            wx.hideLoading();
            return;
          }
        });

      }
    }
  },
  /**
   * 删除购物车中的商品
   * @param {Event} e - 触发事件的对象，包含当前商品的id
   * @description 该方法用于从购物车中移除指定的商品，并更新本地存储和页面数据
   * 1. 获取触发事件的商品id
   * 2. 查找购物车中对应商品的索引
   * 3. 如果找到商品，则从购物车数组中移除该商品
   * 4. 更新本地存储中的购物车数据
   * 5. 更新页面的购物车数据
   */
  delShoppingCartGoods(e) {
    let that = this;
    let id = e.currentTarget.dataset.id;
    let shoppingCart = that.data.shoppingCart;
    let shoppingCartIndex = shoppingCart.findIndex(item => item.id === id);
    if (shoppingCartIndex != -1) {
      shoppingCart.splice(shoppingCartIndex, 1);
      wx.setStorageSync('shoppingCart' + that.data.shop_id, shoppingCart)
      let totalAmount = shoppingCart.reduce((total, item) => that.gshNum(that.gshNum(total) + that.gshNum(item.totalAmount)), 0);
      let totalNum = shoppingCart.reduce((total, item) => total + item.num, 0);
      that.setData({
        shoppingCart,
        totalAmount,
        totalNum
      })
      if (shoppingCart.length < 1) {
        that.setData({
          totalAmount: 0,
          totalNum: 0,
          showShoppingCart: false
        })
      }
    }
  },

  //获取当前时间戳
  getThisSjc() {
    let now = new Date();
    return Math.floor(now.getTime() / 1000);
  },

  //检查是否登录
  checkLogin() {
    var that = this;
    //检查是否登录
    if (this.data.is_login == 0) {
      wx.showModal({
        title: '温馨提示',
        content: that.data.noRegisterContent,
        complete: (res) => {
          if (res.confirm) {
            //跳转注册界面
            wx.setStorageSync('loginHeaderUrl', '/pages/shoppingMall/detail?shop_id=' + that.data.shop_id + "&id=" + that.data.id);
            wx.setStorageSync('loginHeaderType', 'redirectTo')
            if (res.confirm) {
              //跳转注册界面
              wx.redirectTo({
                url: '/pages/login/select-login/select-login'
              })
            }
          }
        }
      })
      return false;
    } else {
      return true;
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;
    var is_share = options.is_share;
    var sceneInfo = options.scene;
    if (!sceneInfo) {
      //不是通过扫码进入
      //商品id
      var id = options.id;
      if (id == '' || id == null || id == undefined) {
        app.showTip('未获取到商品ID哦');
        setTimeout(function () {
          wx.navigateBack({
            delta: 1
          })
        }, 1500);
        return;
      } else {
        that.setData({
          id: id
        });
      }

      //获取商城id
      var shop_id = wx.getStorageSync('shop_id');
      if (shop_id == '' || shop_id == null || shop_id == undefined) {
        //看参数里是否存在shop_id
        shop_id = options.shop_id;
        if (shop_id == '' || shop_id == null || shop_id == undefined) {
          showTip('请先选择商城');
          setTimeout(function () {
            wx.navigateBack({
              delta: 1
            })
          }, 1500);
        }
      }
      that.setData({
        shop_id: shop_id
      });
    } else {
      //是通过扫码进入
      var sceneArr = sceneInfo.split("-");
      var id = sceneArr[0];
      var shop_id = sceneArr[1];
      that.setData({
        id: id,
        shop_id: shop_id
      });
      is_share = 1;
    }

    //判断返回的跳转路径
    if (is_share == 1) {
      that.setData({
        ['defaultData.isShare']: 1
      });
    }

    //获取缓存中的openid
    var openid = wx.getStorageSync('ly24_openid');

    if (openid == '') {
      //缓存中没有openid
      //获取所需页面信息
      wx.login({
        success: function (res) {
          if (res.code) {
            //发起网络请求
            wx.request({
              url: that.data.baseUrl + 'getOpenid.php',
              method: 'POST',
              data: {
                'code': res.code
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: function (res) {
                //缓存微信openid
                wx.setStorageSync('ly24_openid', res.data.openid);
                that.setData({
                  openid: res.data.openid
                });

                //获取本页数据
                that.getShoppingMailDetailPageInfo(res.data.openid, id, shop_id);
              },
              fail: function (res) {}
            });
          }
        }
      });
    } else {
      that.setData({
        openid: openid
      });

      //获取本页数据
      that.getShoppingMailDetailPageInfo(openid, id, shop_id);
    }

    //调用分享
    //that.getShareInfo();
  },

  //获取本页数据
  getShoppingMailDetailPageInfo(openid, id, shop_id) {
    var that = this;

    //获取发放权益的缓存
    var is_send_welfare = 0;
    var sendTimestamp = wx.getStorageSync('sendTimestamp');
    if (sendTimestamp == '' || sendTimestamp == null || sendTimestamp == undefined) {
      var timestamp = new Date().getTime();
      //缓存权益发放标识
      wx.setStorageSync('sendTimestamp', timestamp);
      is_send_welfare = 1;
    } else {
      //存在发放标识
      var timestamp = new Date().getTime();
      if (timestamp - sendTimestamp > 15000) {
        //缓存已超过10s
        is_send_welfare = 1;
        //重置发放时间戳
        wx.setStorageSync('sendTimestamp', timestamp);
      }
    }

    wx.showLoading({
      title: '数据加载中...',
      mask: true
    });

    //发起网络请求
    wx.request({
      url: that.data.baseUrl + 'getShoppingMailDetailPageInfo.php',
      method: 'POST',
      data: {
        'openid': openid,
        'id': id,
        'shop_id': shop_id,
        'is_send_welfare': is_send_welfare
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          //重新赋值后台请求数据
          that.setData({
            bannerArr: res.data.bannerList,
            specificationsArr: res.data.specificationsArr,
            minSellingPrice: res.data.minSellingPrice,
            maxOriginalPrize: res.data.maxOriginalPrize,
            yxTotal: res.data.yxTotal,
            commentTotal: res.data.commentTotal,
            goodsInfo: res.data.goodsInfo,
            noRegisterContent: res.data.noRegisterContent,
            curSpecifications: res.data.specificationsArr[0].id,
            is_login: res.data.is_login,
            mySf: res.data.mySf,
            shareTitle: res.data.goodsInfo.goods_name,
            shareImg: res.data.bannerList[0].img_path
          });

          //初始化规格的值
          var chooseIndex = res.data.chooseSpecsIndex;
          that.setData({
            inventory: res.data.specificationsArr[chooseIndex].inventory,
            childGoodsPrice: res.data.specificationsArr[chooseIndex].price,
            childOriginalPrice: res.data.specificationsArr[chooseIndex].originalPrice,
            specsImg: res.data.specificationsArr[chooseIndex].imgPath
          });
        } else {
          app.showTip(res.data.msg);
          setTimeout(function () {
            wx.navigateBack({
              delta: 1
            });
          }, 1500);
        }
      },
      fail: function () {
        wx.hideLoading();
      }
    });
  },

  //获取微信分享信息
  /*getShareInfo() {
    var that = this;
    wx.request({
      url: that.data.baseUrl + 'getShareInfo.php',
      method: 'POST',
      data: {

      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        that.setData({
          shareTitle: res.data.shareTitle,
          shareImg: res.data.shareImg
        });
      },
      fail: function (res) {}
    });
  },*/

  //跳转用户评论
  toComment() {
    wx.navigateTo({
      url: '/pages/shoppingMall/evaluateList?id=' + this.data.id
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let that = this;
    if (wx.getStorageSync('shoppingCart' + that.data.shop_id)) {
      let shoppingCart = wx.getStorageSync('shoppingCart' + that.data.shop_id);
      let totalAmount = shoppingCart.reduce((total, item) => that.gshNum(that.gshNum(total) + that.gshNum(item.totalAmount)), 0);
      let totalNum = shoppingCart.reduce((total, item) => total + item.num, 0);
      console.log(wx.getStorageSync('shoppingCart' + that.data.shop_id), 'shoppingcart');
      that.setData({
        shoppingCart,
        totalAmount,
        totalNum
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    var that = this;
    return {
      title: that.data.shareTitle,
      path: '/pages/shoppingMall/detail?shop_id=' + that.data.shop_id + "&id=" + that.data.id + "&is_share=1",
      imageUrl: that.data.shareImg,
      success: function (res) {

      },
      fail: function (res) {

      }
    }
  }
})